<?php

namespace app\install\controllers;

class Index
{
    public function __construct()
    {
        self::checkInstall();
    }

    /**
     * 显示安装首页
     */
    public function index()
    {
        $data = [
            'page_title' => '准备 - 安装程序',
        ];

        return view('install/index', $data);
    }

    public function first()
    {
        $write_dir = [
            '../config/',
            '../public/uploads',
            '../runtime/',
            '../runtime/caches',
            '../runtime/logs',
            '../runtime/sessions',
        ];

        $write = [];
        foreach ($write_dir as &$dir) {
            $write[$dir] = is_writable('./' . $dir);
        }

        $data = [
            'page_title'  => '目录检测 - 安装程序',
            'php_version' => version_compare(phpversion(), "7.0.0", ">="),
            'write'       => $write,
            'succeed'     => 1,
        ];

        return view('install/first', $data);
    }

    public function last()
    {
        $data = [
            'page_title'  => '写数据库 - 安装程序',
        ];

        return view('install/last', $data);
    }

    public function submit()
    {
        $config_file = ROOT_PATH . 'config/app.php';
        $lock_file = ROOT_PATH . 'config/install_lock.php';

        if (file_exists($lock_file)) {
            die('程序已安装完毕。');
        }

        if (REQUEST_TYPE === 'post') {
            $data = [
                'db' => [
                    'driver'   => 'mysql',
                    'host'     => post('host'),
                    'database' => post('database'),
                    'username' => post('username'),
                    'password' => post('password'),
                    'charset'  => 'utf8mb4',
                    'port'     => 3306,
                    'prefix'   => post('prefix'),
                ]
            ];

            try {
                write_config($config_file, $data);
                self::writeLockFile();

                return redirect('/');
            } catch (\Throwable $th) {
                throw '写入配置失败。';
            }

        }
    }

    /**
     * 写入安装锁文件
     */
    private static function writeLockFile()
    {
        $locked_file = ROOT_PATH . 'config/install_lock.php';
        if (file_exists($locked_file)) {
            return TRUE;
        }

        file_put_contents($locked_file, '');
    }

    /**
     * 检测是否安装
     */
    private static function checkInstall()
    {
        $lock_file = ROOT_PATH . 'config/install_lock.php';

        $data = [
            'page_title' => '程序已安装完毕',
        ];

        if (file_exists($lock_file)) {
            view('install/installed', $data);
            die();
        }
    }
}
